package com.lry.basic.redis;

import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

public class ReentrantRedisLock {
    //<key,重入次数>
    private final ThreadLocal<Map<String,Integer>> locks = new MapThreadLocal();
    private static class MapThreadLocal extends ThreadLocal<Map<String, Integer>> {
        @Override
        protected Map<String, Integer> initialValue() {
            return new HashMap();
        }
    }


    private Jedis jedis;
    private int expireTime;//过期时间ms
    private String reqId;

    public ReentrantRedisLock(Jedis jedis,int expireTime,String reqId){
        this.jedis = jedis;
        this.expireTime = expireTime;
        this.reqId = reqId;
    }


    public boolean lock(String key){
        Map<String,Integer> refs = locks.get();
        Integer refCount = refs.get(key);

        if(null!=refCount){
            refs.put(key,refCount+1);
            return true;
        }

        boolean ok = RedisLock.tryGetDistributedLock(jedis,key,reqId,expireTime);
        if(!ok)
            return false;

        refs.put(key,1);
        return true;
    }


    public boolean unlock(String key){
        Map<String,Integer> refs = locks.get();
        Integer refCount = refs.get(key);

        if(null==refCount){
            return false;
        }
        refCount-=1;
        if(refCount>0){
            refs.put(key,refCount);
        }else{
            refs.remove(key);
            RedisLock.releaseDistributedLock(jedis,key,reqId);
        }
        return true;
    }



}
